<script lang="ts" setup>
import type { TreeInstance } from 'element-plus';

/** 右侧内容业务逻辑开始 */
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { SystemDeptApi } from '#/api/system/dept';
import type { SystemPostApi } from '#/api/system/post';

import { onMounted, reactive, ref, watch } from 'vue';

import { ColPage, Page, useVbenModal } from '@vben/common-ui';
/** 左侧内容业务逻辑结束 */
import { IconifyIcon } from '@vben/icons';

import {
  ElButton,
  ElInput,
  ElLoading,
  ElMessage,
  ElMessageBox,
  ElTooltip,
  ElTree,
} from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getDeptList } from '#/api/system/dept';
import { deletePost, getPage } from '#/api/system/post';
import { $t } from '#/locales';

import { useColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';

const props = reactive({
  leftCollapsedWidth: 5,
  leftCollapsible: true, // 左侧可折叠
  leftMaxWidth: 50, // 左侧最大宽度百分比
  leftMinWidth: 15, // 左侧最小宽度百分比
  leftWidth: 20,
  resizable: true, // 可拖动调整宽度
  rightWidth: 80,
  splitHandle: true, // 显示拖动手柄
  splitLine: true, // 显示拖动分隔线
});

/** 业务逻辑 */
/** 左侧内容业务逻辑开始 */
const deptTreeRef = ref<TreeInstance>();
// 部门ID
const deptId = ref(0);
// 1. 添加表单状态引用
const searchForm = ref<Record<string, any>>({});

const deptTree = ref<SystemDeptApi.SystemDept[]>([]); // 部门树
const deptLoading = ref(false); // 加载部门列表
const defaultCheckedKeys = ref<number[]>([]); // 默认选中
const filterText = ref('');
interface Tree {
  [key: string]: any;
}
watch(filterText, (val) => {
  deptTreeRef.value!.filter(val);
});
onMounted(() => {
  loadDeptTree();
});
const filterNode = (value: string, data: Tree) => {
  if (!value) return true;
  return data.label.includes(value);
};
/** 加载部门树 */
async function loadDeptTree() {
  deptLoading.value = true;
  try {
    const data = await getDeptList();
    deptTree.value = data;
  } finally {
    deptLoading.value = false;
  }
}
// 点击选中菜单
const handleNodeClick = (nodeData, node, nodeComponent) => {
  deptId.value = nodeData.deptId;
  // 先显示加载状态（保持DOM稳定）
  const loadingInstance = ElLoading.service({
    target: '.vxe-table--body-wrapper',
    lock: true,
  });
  try {
    gridApi.query({ ...searchForm.value, deptId: deptId.value });
  } finally {
    loadingInstance.close();
  }
};

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    fieldMappingTime: [['createTime', ['startTime', 'endTime']]],
    schema: useGridFormSchema(),
    submitOnChange: false,
    // 设置初始不展开
    collapsed: true,
    handleValuesChange: (values) => {
      searchForm.value = values;
    },
  },
  gridOptions: {
    columns: useColumns(onActionClick),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getPage({
            page: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
            deptId: deptId.value,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'postId',
    },

    toolbarConfig: {
      custom: true,
      export: false,
      refresh: { code: 'query' },
      search: true,
      zoom: true,
    },
  } as VxeTableGridOptions<SystemPostApi.SystemPost>,
});

function onActionClick(e: OnActionClickParams<SystemPostApi.SystemPost>) {
  switch (e.code) {
    case 'delete': {
      onDelete(e.row);
      break;
    }
    case 'edit': {
      onEdit(e.row);
      break;
    }
  }
}

function onEdit(row: SystemPostApi.SystemPost) {
  formModalApi.setData(row).open();
}

function onDelete(row: SystemPostApi.SystemPost) {
  ElMessageBox.confirm(`确定删除【${row.postName}】吗`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const loadingInstance = ElLoading.service({
        lock: true,
        text: $t('ui.actionMessage.deleting', [row.postName]),
        spinner: 'el-icon-loading', // 使用内置图标名
        background: 'rgba(0, 0, 0, 0.7)',
      });
      deletePost(row.postId)
        .then(() => {
          ElMessage.success(
            $t('ui.actionMessage.deleteSuccess', [row.postName]),
          );
          refreshGrid();
        })
        .finally(() => {
          loadingInstance.close();
        });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      });
    });
}

function refreshGrid() {
  gridApi.query();
}

function onCreate() {
  formModalApi.setData({}).open();
}
/** 右侧内容业务逻辑结束 */
</script>
<template>
  <ColPage auto-content-height v-bind="props">
    <!-- 左侧内容开始 -->
    <template #left="{ isCollapsed, expand }">
      <div v-if="isCollapsed" @click="expand">
        <ElTooltip class="box-item" effect="dark" content="点击展开左侧">
          <ElButton circle type="primary">
            <template #icon>
              <IconifyIcon class="text-2xl" icon="bi:arrow-right" />
            </template>
          </ElButton>
        </ElTooltip>
      </div>
      <div
        v-else
        :style="{ minWidth: '200px' }"
        class="border-border bg-card mr-2 rounded-[var(--radius)] border p-2"
      >
        <Page auto-content-height>
          <ElInput
            v-model="filterText"
            class="mb-2 w-60"
            placeholder="请输入"
          />
          <ElTree
            ref="deptTreeRef"
            :data="deptTree"
            node-key="deptId"
            default-expand-all
            :default-checked-keys="defaultCheckedKeys"
            :filter-node-method="filterNode"
            @node-click="handleNodeClick"
          />
        </Page>
      </div>
    </template>
    <!-- 左侧内容结束 -->
    <!-- 右侧内容开始 -->
    <FormModal @success="refreshGrid" />
    <Grid :table-title="$t('system.post.list')">
      <template #toolbar-tools>
        <ElButton type="primary" @click="onCreate">
          {{ $t('ui.actionTitle.create', [$t('system.post.name')]) }}
        </ElButton>
      </template>
    </Grid>
    <!-- 右侧内容结束 -->
  </ColPage>
</template>
